#!/usr/bin/python
import os;
from video_lib.video_db import db_init
from video_lib.video_db.movie_queue import movie_queue
from sqlalchemy.orm import sessionmaker
from sqlalchemy import and_
import datetime 
import time
class Download:
	#create session
	DownloadSession 		= sessionmaker(bind= db_init.engine)
	session_download 		= DownloadSession();	


	def __init__(self,vq_e):
		self.video_url=vq_e.video_url;
		self.format=[22,18,34,5];
		self.file_extend={"22":".mp4","18":".mp4","34":".flv","5":".flv","100":".mp4"}
		self.video_name=str(int(time.time()))+"_"+str(vq_e.id)
		self.video_title="";
		self.video_des  ="";
		self.video_fmt	="";
		self.download_path  = "/home/work/download/youtube/"+str(datetime.date.today())
		self.download_status = 'downloading';
		self.video_queue_element = vq_e;
		print id(vq_e);
		print id(self.video_queue_element) 
		if   not os.path.exists(self.download_path):
		     os.mkdir(self.download_path)
		Download.session_download.add(self.video_queue_element);

	def download_start(self):
		self.video_queue_element.video_status = 'downloading';
		Download.session_download.commit()
	def download_file(self):
		r  =0;
		for f in self.format:
			cmd ="./youtube-dl";
			self.video_fmt = str(f);
			cmd +=" -f "	+str(f);
			cmd +=" '"	+self.video_url;
			cmd +="' -r "	+"1m"
			cmd +=" -o "	+ self.download_path+"/"+self.video_name+self.file_extend[str(f)];
			re  = os.system(cmd);
			if (re == 0):
				print "succ " + cmd;
				self.download_status = 'wait_convert';
				self.video_queue_element.video_downloadname	=  self.download_path+"/"+self.video_name+self.file_extend[str(f)];
				return 0;
			else:
				print "fail " + cmd;
		print "fail all: "+self.video_url;
		self.download_status	= 'download_fail';
		return -1;	
	def download_end(self):
		self.video_queue_element.video_status 		= self.download_status;
		self.video_queue_element.video_format 		= self.video_fmt;
		Download.session_download.commit()



if __name__=='__main__':
#	for row in Download.session_download.query(movie_queue).filter(and_(movie_queue.video_status == 'wait_convert', movie_queue.video_from == 'youtube')):
	for row in Download.session_download.query(movie_queue).filter(and_(movie_queue.video_status == 'wait_download', movie_queue.video_from == 'youtube')).limit(1):

		p = Download(row)
		print row.video_url ,row.video_downloadname,row.id

		p.download_start();
		p.download_file();
		p.download_end();
		#row.video_status = 'downloading'
		#print row.video_url ,row.video_downloadname,row.id
		#break;
#download=Download("http://www.youtube.com/watch?v=-D7uILB3GkQ","output/11");
#download.get_info();
#print download.download_file();
#d= os.system('lx -lh')
#if d == 0 :

#print d
